import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { MatDialogRef } from '@angular/material';
import { markAllAsTouched } from 'app/modules/base/helper';
import { ZoneService, ZoneModel, Zone } from '../../services/zone.service';

@Component({
  selector: 'm-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
})
export class AddComponent implements OnInit {
  constructor(private dialog: MatDialogRef<AddComponent>, private zoneService: ZoneService) {}
  @ViewChild(NgForm) ngForm: NgForm;
  @Input() value: Zone[];
  ngOnInit() {}

  cancel() {
    this.dialog.close();
  }
  async create() {
    markAllAsTouched(this.ngForm.form);
    if (this.ngForm.invalid) {
      return;
    }
    const level_struct = this.ngForm.value.parent_level_struct;
    let name = this.ngForm.value.name.trim();
    this.ngForm.form.patchValue({
      name
    })
    if(!name) return;
    await this.zoneService.create({
      ...this.ngForm.value,
      parent_level_struct: level_struct === '/' ? '' : level_struct,
    });
    this.dialog.close(true);
  }
}
